import 'package:flutter/foundation.dart';
import 'package:share_fit/app/controllers/base/base_controller.dart';
import 'package:share_fit/app/tools/log_utils.dart';
import 'package:share_fit/app/ute/uteped_const.dart';
import 'package:share_fit/app/ute/uteped_device.dart';

import 'spo2_setting_state.dart';

class Spo2SettingLogic extends BaseController {
  final Spo2SettingState state = Spo2SettingState();

  static const keySpo2Period = "spo2Period";

  void setContinuousBloodOxygenEnable(value) {
    showLoading();
    state.isContinuousBloodOxygen.value = value;
    bRemoteReqAsync(UTEPedConst.methodSetContinuousBloodOxygen, {UTEPedConst.keyEnable: value})
        .then((success) => _onSetContinuousBloodOxygen(success, value));
  }

  void setPeriod(min) {
    state.periodMin.value = min;
    _setShowHour(min);
    save(keySpo2Period, min);
  }

  void _setShowHour(min) {
    if (min < 60) {
      state.period.value = min.toString();
      state.showHour.value = false;
    } else {
      state.period.value = (min ~/ 60).toString();
      state.showHour.value = true;
    }
  }

  @override
  String getRemotePath() {
    return UTEPedConst.pathDeviceOptions;
  }

  @override
  String getStoragePath() {
    return UTEPedConst.pathDevice;
  }

  @override
  void initState() {
    state.isContinuousBloodOxygen.value = read(UTEPedConst.methodSetContinuousBloodOxygen, defaultValue: false);
    state.periodMin.value = read(keySpo2Period, defaultValue: 60);
    _setShowHour(state.periodMin.value);
  }

  @override
  void onRemoteEvent(event, method) {
    // empty
  }

  void _onSetContinuousBloodOxygen(success, value) {
    cancelLoading();
    if (success) {
      save(UTEPedConst.methodSetContinuousBloodOxygen, value);
    }
    else {
      state.isContinuousBloodOxygen.value = !value;
    }
    if (kDebugMode) {
      UTEPedDevice.instance.getDefaultConfiguration().then((value) => logger.d(value));
    }
  }
}
